<template>
  <div class="p-2">
    <!-- <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="群组名称" prop="gwDevGroupName">
            <el-input v-model="queryParams.gwDevGroupName" placeholder="请输入群组名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition> -->

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" /> -->
        </el-row>
      </template>

      <el-table v-loading="loading" :data="groupList">
        <el-table-column label="id" align="center" prop="id" v-if="false" />
        <el-table-column label="群组名称" align="center" prop="gwDevGroupName" />
        <el-table-column label="开关" align="center" prop="workState">
          <template #default="scope">
            <el-switch v-model="scope.row.workState" :active-value="true" :inactive-value="false" @click="switchChange(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="调光" align="center" prop="percentage">
          <template #default="scope">
            <el-slider v-model="scope.row.percentage" :max="100" :min="0" :default-value="0" @change="percentageChange(scope.row)" :disabled="!scope.row.workState" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
            </el-tooltip>
            <el-tooltip content="添加设备" placement="top">
              <el-button link type="primary" icon="CirclePlus" @click="handleAddEqu(scope.row)" />
            </el-tooltip>
            <el-tooltip content="查询" placement="top">
              <el-button link type="primary" icon="Search" @click="handleQueryEqu(scope.row)" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :total="total" 
        v-model:page="queryParams.pageNum" 
        v-model:limit="queryParams.pageSize" 
        @pagination="getList" 
      />
    </el-card>
    <!-- 新增或修改群组对话框 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="500px"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      append-to-body
      destroy-on-close
    >
      <el-form ref="groupFormRef" :model="groupForm" :rules="rules" label-width="80px">
        <el-form-item label="群组名称" prop="gwDevGroupName">
          <el-input v-model="groupForm.gwDevGroupName" placeholder="请输入群组名称" />
        </el-form-item>
        <el-form-item label="网关设备" prop="gwid">
          <el-select v-model="groupForm.gwid" placeholder="请选择网关设备" style="width: 100%" :disabled="dialog.title == '修改群组'" >
            <el-option v-for="item in gatewayOptions" :key="item.id" :label="item.deviceName" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 绑定设备对话框 -->
    <el-dialog
      title="新增设备"
      v-model="dialogDevice.visible"
      width="40%"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      append-to-body
      destroy-on-close
    >
      <!-- <el-form ref="queryDeviceParamsRef" :model="queryDeviceParams" :inline="true" label-width="40px">
        <el-form-item label="名称" prop="deviceName">
          <el-input v-model="queryDeviceParams.deviceName" placeholder="请输入设备名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQueryDevice">搜索</el-button>
          <el-button icon="Refresh" @click="resetQueryDevice">重置</el-button>
        </el-form-item>
      </el-form> -->
      <el-table
        :data="addDeviceList"
        bordered
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="在线状态" align="center" width="140">
          <template #default="scope">
            <span v-if="scope.row.state == 'online'" style="color: #6de88c">在线</span>
            <span v-else style="color: #dea959">离线</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :total="totalDevice" 
        v-model:page="queryDeviceParams.pageNum" 
        v-model:limit="queryDeviceParams.pageSize" 
        @pagination="getDeviceList" 
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitDeviceForm">确 定</el-button>
          <el-button @click="cancelDevice">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查询>设备列表抽屉 -->
    <el-drawer
      title="设备列表"
      placement="right"
      :closable="false"
      :model-value="drawerVisible"
      @update:model-value="handleDrawerClose"
      size="40%"
    >
      <el-button @click="handleDrawerDelete" type="primary" style="margin-bottom: 10px">批量删除</el-button>
      <el-table
        :data="drawerList"
        bordered
        @selection-change="handleDrawerSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="在线状态" align="center" width="140">
          <template #default="scope">
            <span v-if="scope.row.state == 'online'" style="color: #6de88c">在线</span>
            <span v-else style="color: #dea959">离线</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :total="totalDrawer" 
        v-model:page="queryDrawerParams.pageNum" 
        v-model:limit="queryDrawerParams.pageSize" 
        @pagination="getDrawerList" 
      />
    </el-drawer>
  </div>
</template>

<script setup name="Group" lang="ts">
import { getGroupList, getGatewayAll, addGroup, aedGroupDevice, getDeviceInGw, getDeviceByGroup } from './api/group.api'
import { ComponentInternalInstance } from 'vue'
import { FormInstance, rowContextKey } from 'element-plus'
import { group } from 'console'

const drawerVisible = ref(false) // 右侧抽屉-查询>设备列表
const addDeviceList = ref()
const drawerList = ref()

const groupList = ref()
const { proxy } = getCurrentInstance() as ComponentInternalInstance

const buttonLoading = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref<Array<string | number>>([])
const de_ids = ref<Array<string | number>>([])
const total = ref(0)
const totalDrawer = ref(0)
const totalDevice = ref(0)

const groupFormRef = ref<FormInstance>()
const queryDeviceParamsRef = ref<FormInstance>()

const dialog = reactive<DialogOption>({
  visible: false,
  title: '',
})
const dialogDevice = reactive<DialogOption>({
  visible: false
})

const groupForm = reactive({
  id: '',
  gwDevGroupName: '',
  gwid: '',
})
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // gwDevGroupName: undefined,
  },
  queryDeviceParams: {
    pageNum: 1,
    pageSize: 10,
    deviceName: undefined,
    addr: undefined
  },
  queryDrawerParams: {
    pageNum: 1,
    pageSize: 10
  },
  rules: {
    id: [{ required: true, message: 'id不能为空', trigger: 'blur' }],
    gwDevGroupName: [{ required: true, message: '群组名称不能为空', trigger: 'blur' }],
    gwid: [{ required: true, message: '网关设备不能为空', trigger: 'change' }],
  },
})

const { queryParams, queryDeviceParams, queryDrawerParams, rules } = toRefs(data)

/** 查询群组列表 */
const getList = () => {
  loading.value = true
  getGroupList(
    queryParams.value
  ).then((res) => {
    groupList.value = res.data.rows
    total.value = res.data.total
  }).finally(() => {
    loading.value = false
  })
}
/* // 搜索按钮操作
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}
// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
} */

/** 新增/修改页面 */
// 网关设备下拉框
const gatewayOptions = ref<{ id: string; deviceName: string }[]>([])
const getGatewayAllOptions = () => {
  getGatewayAll({
    productKey: '7GhmGTj27mehmpaJ'
  }).then((res) => {
    gatewayOptions.value = res.data || []
  })
}
getGatewayAllOptions()
// 新增群组按钮操作
const handleAdd = async () => {
  dialog.visible = true
  dialog.title = '添加群组'
}
// 修改按钮操作
const handleUpdate = (row) => {
  dialog.visible = true
  dialog.title = '修改群组'
  nextTick(async () => {
    Object.assign(groupForm, row)
  })
}
// 提交按钮
const submitForm = async () => {
  // 验证表单数据
  await groupFormRef.value?.validate()
  const aeText = dialog.title == '添加群组' ? '添加' : '修改'
  const aeData = dialog.title == '添加群组' ?{
    gwDevGroupName: groupForm.gwDevGroupName,
    gwid: groupForm.gwid,
    workState: false // 工作状态,刚添加默认为关
  } : {
    id: groupForm.id,
    gwDevGroupName: groupForm.gwDevGroupName
  }
  await addGroup(aeData).then((res) => {
    if (res.code === 200) {
      ElMessage.success(aeText + '成功')
      cancel()
      getList()
    } else {
      ElMessage.error(res.message)
    }
  })
}
// 开关按钮
const switchChange = async (row) => {
  const aeData = {
    groupid: row.id,
    gwId: row.gwid,
    workstate: row.workState,
    percentage: row.workState == 'true' ? row.percentage : 0 // 工作状态,开关打开时才可调光
  }
  await aedGroupDevice(aeData).then((res) => {
    if (res.code === 200) {
      ElMessage.success('开关成功')
      getList()
    } else {
      ElMessage.error(res.message)
    }
  })
}
// 调光按钮
const percentageChange = async (row) => {
  const aeData = {
    groupid: row.id,
    gwId: row.gwid,
    percentage: row.percentage,
    workstate: row.percentage == 0 ? false : row.workState, // 工作状态,调光为0时默认为关
  }
  await aedGroupDevice(aeData).then((res) => {
    if (res.code === 200) {
      ElMessage.success('调光成功')
      getList()
    } else {
      ElMessage.error(res.message)
    }
  })
}
// 取消按钮
const cancel = () => {
  reset()
  dialog.visible = false
}
// 表单重置
const reset = () => {
  groupForm.id = ''
  groupForm.gwDevGroupName = ''
  groupForm.gwid = ''
  groupFormRef.value?.resetFields()
}

/** 新增设备页面 */
// 保存当前行的群组信息
const currentGroupInfo = ref<{ id: string, gwid: string }>()
// 新增设备按钮操作
const handleAddEqu = (row) => {
  dialogDevice.visible = true
  currentGroupInfo.value = row // 当前行的群组信息
  getDeviceList()
}
// 查询群组未入网设备列表
const getDeviceList = async () => {
  await getDeviceInGw({
    ingw: false,
    pageNum: queryDeviceParams.value.pageNum,
    pageSize: queryDeviceParams.value.pageSize
  }).then((res) => {
    addDeviceList.value = res.data.rows
    totalDevice.value = res.data.total
  })
}
// 提交按钮
const submitDeviceForm = async () => {
  await aedGroupDevice({
    devids: ids.value,
    groupid: currentGroupInfo.value?.id,
    gwId: currentGroupInfo.value?.gwid,
    type: 'ae' // ae增加/修改，de删除
  }).then((res) => {
    if (res.code === 200) {
      ElMessage.success('添加成功')
      cancelDevice()
      getList()
    } else {
      ElMessage.error(res.message)
    }
  })
}
// 选择条数
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id)
  console.log(ids.value)
}
// 搜索按钮操作
const handleQueryDevice = () => {
  queryDeviceParams.value.pageNum = 1
  getDeviceList()
}
// 重置按钮操作
const resetQueryDevice = () => {
  queryDeviceParamsRef.value?.resetFields()
  handleQueryDevice()
}
// 取消按钮
const cancelDevice = () => {
  resetQueryDevice()
  dialogDevice.visible = false
}


/** 查询群组已选设备列表 */
// 查询>设备列表操作
const handleQueryEqu = async (row) => {
  loading.value = true
  drawerVisible.value = true
  currentGroupInfo.value = row // 当前行的群组信息
  getDrawerList()
  loading.value = false
}
// 查询群组已入网设备列表
const getDrawerList = async () => {
  await getDeviceByGroup({
    groupid: currentGroupInfo.value?.id,
    gwId: currentGroupInfo.value?.gwid,
    pageNum: queryDeviceParams.value.pageNum,
    pageSize: queryDeviceParams.value.pageSize
  }).then((res) => {
    drawerList.value = res.data.rows
    totalDrawer.value = res.data.total
  })
}
const handleDrawerDelete = () => {
  ElMessageBox.confirm('是否删除选中设备?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    aedGroupDevice({
      devids: de_ids.value,
      groupid: currentGroupInfo.value?.id,
      gwId: currentGroupInfo.value?.gwid,
      type: 'de' // ae增加/修改，de删除
    }).then((res) => {
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList()
      } else {
        ElMessage.error(res.message)
      }
    })
  })
}
// 选择条数
const handleDrawerSelectionChange = (selection) => {
  de_ids.value = selection.map((item) => item.id)
  console.log(de_ids.value)
}
const handleDrawerClose = (value: boolean) => {
  if (!value) {
    drawerVisible.value = false
  }
}

/** 删除按钮操作 */
const handleDelete = (row) => {
  ElMessageBox.confirm('是否删除群组-' + row.gwDevGroupName + '?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    addGroup({
      id: row.id,
      del: 'true' // 默认为false，true为删除
    }).then((res) => {
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList()
      } else {
        ElMessage.error(res.message)
      }
    })
  })
}

onMounted(() => {
  getList()
})
</script>
